package ogmios.processes;

import javax.swing.*;
import java.io.*;
import ogmios.core.*;
import java.lang.reflect.*;

/**
 * A thread that will write the contents of an input stream into a DefaultListModel, one line at a time
 */
public class DefaultLineInputThread extends Thread
{

    public DefaultListModel depositList;
    protected BufferedReader input;
    protected Runnable updater;
    protected String line;

    public DefaultLineInputThread(DefaultListModel newDeposit, InputStream stream)
    {
        depositList = newDeposit;
        input = new BufferedReader(new InputStreamReader(stream));
        updater =
            new Runnable()
        {
            public void run()
            {
                depositList.addElement(line);
            }
        };
        setDaemon(true);
    }

    public void run()
    {
        try
        {
            while ((line = input.readLine()) != null)
            {
                try
                {
                    SwingUtilities.invokeAndWait(updater);
                }
                catch (InterruptedException ex)
                {
                    OgmiosUtilities.showErrorBox(null, ex, "Process:Input Error");
                }
                catch (InvocationTargetException e)
                {
                    OgmiosUtilities.showErrorBox(null, e, "Process:Input Error");
                }
            }
            input.close();
        }
        catch (IOException ex)
        {
            OgmiosUtilities.showErrorBox(null, ex, "Process:Input Error");
        }
    }


}
